//
//  RLocation.m
//  Riji
//
//  Created by  on 2022/8/21.
//

#import "RLocation.h"
#import <CoreLocation/CoreLocation.h>

@interface RLocation()<CLLocationManagerDelegate>
@property(nonatomic,strong)CLLocationManager* manger;

@end
@implementation RLocation
- (CLLocationManager *)manger{
    
    if (!_manger) {
        _manger = [[CLLocationManager alloc]init];
        _manger.delegate = self;
        _manger.desiredAccuracy = kCLLocationAccuracyBest;
        _manger.distanceFilter = kCLDistanceFilterNone;
        [_manger requestWhenInUseAuthorization];
    }
    return _manger;
}
- (void)setLocation:(void (^)(NSString * _Nonnull))location{
    _location = location;
    // 确定用户的位置服务是否启用
    if ([CLLocationManager locationServicesEnabled] == NO){
        return [RLHud msg:LS(@"未开启定位权限")];
    }
    // 位置服务是在设置中禁用
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        return [RLHud msg:LS(@"位置服务已被禁用")];
    }
    
    [self.manger startUpdatingLocation];
}
- (void)updateWeather:(NSString *)address{
    for (RCityModel *city in APP.city) {
        if ([address containsString:city.city]) {
            [CCHttp http].basicURLString = @"";
            NSString *cityutf8 = [city.city stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *url = [NSString stringWithFormat:@"%@?key=%@&city=%@",api_weather,kkey,cityutf8];
            [CCHttp get:url para:nil header:nil success:^(id  _Nonnull response) {
                int code = [[response valueForKey:@"error_code"] intValue];
                if (code == 0) {
                    NSDictionary * dict = [[response valueForKey:@"result"] valueForKey:@"realtime"];
                    if (self.cityWeather) {
                        NSString *weather = [NSString  stringWithFormat:@"%@ %@℃",LS((NSString*)[dict valueForKey:@"info"]),[dict valueForKey:@"temperature"]];
                        self.cityWeather(weather);
                    }
                }
            } fail:^(NSError * _Nonnull error) { }];
            [CCHttp http].basicURLString = baseurl;
            break;
        }
    }
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations {
    [self.manger stopUpdatingLocation];
    
    CLLocation *location = [locations lastObject];
    ///定位
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            NSLog(@"当前的位置：%@",placeMark.country);//当前的国家
            NSLog(@"当前的位置：%@",placeMark.administrativeArea);//当前的省份
            NSLog(@"当前的位置：%@",placeMark.locality);//当前的城市
            NSLog(@"当前的位置：%@",placeMark.subLocality);//当前的位置
            NSLog(@"当前街道：%@",placeMark.thoroughfare);//当前街道
            NSLog(@"具体地址：%@",placeMark.name);//具体地址
            [self updateWeather:[[placeMark.addressDictionary valueForKey:@"FormattedAddressLines"] firstObject]];
            if (self.location) {
                self.location([[placeMark.addressDictionary valueForKey:@"FormattedAddressLines"] firstObject]);
            }
        }
    }];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    [manager stopUpdatingLocation];
    NSString *errorString;
    NSString *alterTitle;
    NSLog(@"Error: %@",[error localizedDescription]);
    if (self.location) {
        self.location(LS(@"定位失败"));
    }
    switch([error code]) {
        case kCLErrorDenied:
            //Access denied by user
            errorString = @"请在系统设置中开启定位服务\n(设置>隐私>定位服务)";
            alterTitle  = @"定位服务未开启";
            break;
        case kCLErrorNetwork:
            //Probably temporary...
            errorString = @"网络未开启,请检查网络设置";
            alterTitle  = @"提示";
            break;
        default:
            errorString = @"发生位置错误";
            alterTitle  = @"提示";
            break;
    }
    
    UIAlertView *locationFailAlert = [[UIAlertView alloc] initWithTitle:alterTitle message:errorString delegate:self cancelButtonTitle:LS(@"知道了") otherButtonTitles:nil, nil];
    [locationFailAlert show];
}

@end
